//
//  AppDelegate.m
//  WinesMall
//
//  Created by Isaac on 17/8/23.
//  Copyright © 2017年 Isaac. All rights reserved.
//

#import "AppDelegate.h"
#import "TTFirstViewController.h"

#define UMENG_KEY @"57453da667e58eaaac000eff"
#define WX_APPID  @"wx5c07f38be20d0972"                                 //   appstore: @"wx074b46e790c2e531"
#define WX_SECRET @"f4e0cdca21566b17f957aea08585947b"                   //   appstore: @"921768acd38e652abb8028878cc422bf"
/*
 APPID：wx5c07f38be20d0972
 AppSecret：f4e0cdca21566b17f957aea08585947b
 
 */

#define QQ_APPID  @"1104660765"
#define QQ_APPKEY @"jD0TjQpWBtHd9v1q"


@interface AppDelegate ()<UIAlertViewDelegate>
{
    NSDictionary *pushinfo;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    NSLog(@"width:%.2f,--- height:%.2f,--- UI_X_Height:%.2f---UI_Y:%.2f",SCREEN_WIDTH, SCREEN_HEIGHT, UI_X_Height, UI_Y);
    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self setNavigationStyle];
    
    [self pointToMain];
    
    
//    [JPUSHService setupWithOption:launchOptions
//                           appKey:pushAppKey
//                          channel:pushChannel
//                 apsForProduction:isProduction];
    [self configThirdInfo];
    
    NSDictionary*userInfo1 = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    if(userInfo1)
    {
        [self application:[UIApplication sharedApplication] didReceiveRemoteNotification:userInfo1];
    }
    
    


    if (!([userToken isEqualToString:@""] || userToken == nil)) {
        [self updateUserInfo];
    }
    

    
    return YES;
}

- (void)configThirdInfo {
   
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMENG_KEY];
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_APPID appSecret:WX_SECRET redirectURL:nil];
    //设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQ_APPID appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];    //分享
    //新浪
    //    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    //**********************************极光***************************************
    
//    [JPUSHService setBadge:0];//清空badge
    [UIApplication sharedApplication].applicationIconBadgeNumber= 0;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
//        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//                                                          UIUserNotificationTypeSound |
//                                                          UIUserNotificationTypeAlert)
//                                              categories:nil];
    }
    
    
    [[WSMTools wsmTool] appVersionChick];
    
}

#pragma mark - 推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //    NSLog(@"regisger success:%@",deviceToken);
    NSString *token = [NSString stringWithFormat:@"%@",deviceToken];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    
    NSLog(@"token---:   %@",token);
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
//    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    

//    [JPUSHService registerDeviceToken:deviceToken];
    //注册成功，将deviceToken保存到应用服务器数据库中
    
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
//    [JPUSHService setTags:nil aliasInbackground:[OpenUDID value]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        
    });
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
    
}
//自定义推送消息
//- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    NSDictionary * userInfo = [notification userInfo];
//
//    [[PushModel sharedPushmodel] receivemessagenotification:userInfo];
//}

//普通notification

/**
 我给你传的信息里有个extras的键，里面的type=1的时候表示推送的是活动消息，点击后跳转到type_id对应的那个活动页面；type=2的时候表示推送的是新闻的信息，点击后跳转到type_id对应的那条新闻的页面
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    [UIApplication sharedApplication].applicationIconBadgeNumber= 0;
//    [JPUSHService setBadge:0];//清空badge
    // 处理推送消息
//    [JPUSHService handleRemoteNotification:userInfo];
    
#warning 有消息时把个人中心小红点置成红色；
    [TTConfig setNewMessage:NO];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshMine" object:nil];

    
    if (userInfo) {
        
        pushinfo = userInfo;
                NSLog(@"2222%@",userInfo);
        NSInteger pushType =[userInfo[@"type"] integerValue];
        if (pushType == 1) { //跳到活动
//            NSString *type_id = userInfo[@"type_id"];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[userInfo[@"aps"] objectForKey:@"alert"] message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看", nil];
            alertView.tag = pushType;
            [alertView show];
        }else if (pushType == 2){ //跳到新闻
//            NSString *type_id = userInfo[@"type_id"];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[userInfo[@"aps"] objectForKey:@"alert"] message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看", nil];
            alertView.tag = pushType;
            [alertView show];
        }

        
    }
    
}
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"pushinfo:%@",pushinfo);
    if (buttonIndex == 1) {
        switch (alertView.tag) {
            case 1:{  //跳到活动
                [[WSMTools wsmTool] gotoTabBarItemWithTabNum:1];
                [self performSelector:@selector(pointToPage:) withObject:@"1" afterDelay:0.1];

            }
                break;
            case 2:{   //跳到新闻
                [[WSMTools wsmTool] gotoTabBarItemWithTabNum:2];
                [self performSelector:@selector(pointToPage:) withObject:@"2" afterDelay:0.1];

            }
                break;
            
            default:
                break;
        }
        
    }
}
- (void)pointToPage:(NSString *)type {
    NSString *notificationName;
    if ([type isEqualToString:@"1"]) {
        notificationName = @"SeeActivity";
    }else if ([type isEqualToString:@"2"]){
        notificationName = @"SeeNews";
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:notificationName object:@"" userInfo:@{@"type_id":pushinfo[@"type_id"]}];
}
- (void)setNavigationStyle {
    ///设置状态栏字体颜色,    及状态栏和导航栏背景颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//设置状态栏字体为白色
    [[UINavigationBar appearance] setBarTintColor:kWhiteColor];
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:kTextColorOne,NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:17],NSFontAttributeName,nil]];
}

/**
 决定启动app显示到哪里
 */
- (void)pointToMain {
    
    
    NSString *uuidStr = (NSString *)[[WSMTools wsmTool] getUUID];
    NSString *uuid = [SFHFKeychainUtils getPasswordForUsername:@"uuid" andServiceName:SERVICE_NAME error:nil];
    if (!uuid) {
        [SFHFKeychainUtils storeUsername:@"uuid" andPassword:uuidStr forServiceName:SERVICE_NAME updateExisting:1 error:nil];
    }
    NSString *key = (NSString *)kCFBundleVersionKey;
    // 1.从Info.plist中取出版本号
    NSString *version1 = [NSBundle mainBundle].infoDictionary[key];
    // 2.从沙盒中取出上次存储的版本号
    NSString *saveVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
//    if (![version1 isEqualToString:saveVersion]) { // 第一次使用这个版本
//        self.window.rootViewController = [[TTFirstViewController alloc] init];
//        [[NSUserDefaults standardUserDefaults] setObject:version1 forKey:key];
//
//    }else{
        [self gotoMainView];
//    }
   
}
- (void)gotoMainView{
    self.myTabBar = [WSMBaseTabBarController new];
    typedef void (^Animation)(void);
    self.myTabBar.modalPresentationStyle =UIModalPresentationFullScreen;
    
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        self.window.rootViewController = self.myTabBar;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:self.window duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:animation completion:nil];
}

- (void)updateUserInfo {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    



}
- (void)handleSignIn {
    //上次签到成功的时间戳
    double oldTime = [[[NSUserDefaults standardUserDefaults] objectForKey:@"oldTime"] floatValue];
    
    //今日零点的时间戳
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSDate *zeroDate = [calendar dateFromComponents:components];
    NSTimeInterval time = [zeroDate timeIntervalSince1970];
    
    
    //打开app的时间戳     currentDate
    NSTimeInterval nowTime = [currentDate timeIntervalSince1970];

    if (time > oldTime && nowTime > time) {//首次打开
        NSMutableDictionary * parames = [NSMutableDictionary dictionary];
        @weakify(self);
        [TTServerTool postDictionaryResult:API_today_signIn param:parames isNeedToken:YES complete:^(BOOL network, TTPublicResult * result, NSError * error) {
            @strongify(self);
            if (network) {
                
                if (result) {
                    
                    if([result.ErrorCode isEqualToString:@"0"]){
                        
                        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",nowTime] forKey:@"oldTime"];
                        //  显示签到成功的提示
                        
                    }else{
                        
                    }
                    
                }else{
                }
                
            }else{
               
            }
            
        }];
    }
    
    
}


#pragma mark - AliPay
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
   
    return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        
    }else if([url.host isEqualToString:@"pay"]){
        
    }else {
        BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
        if (!result) {
            
        }
        return result;
    }
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
